<template>
  <div class="distribution-goods-manager">
    <!-- 头部操作区 -->
    <div class="manager-header">
      <div class="header-left">
        <h3>分销商品管理</h3>
        <span class="description">管理本校区商品和选择其他校区的分销商品</span>
      </div>
      <div class="header-right">
        <el-button @click="refreshData" icon="el-icon-refresh" size="small">刷新数据</el-button>
        <el-button @click="$emit('close')" size="small">关闭</el-button>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="manager-content" v-loading="loading">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <!-- 本校区商品tab -->
        <el-tab-pane label="本校区商品" name="own">
          <template slot="label">
            <i class="el-icon-goods"></i>
            本校区商品 ({{ ownGoods.length }})
          </template>
          
          <div class="own-goods-section">
            <div class="section-header">
              <div class="search-bar">
                <el-input
                  v-model="ownSearchKeyword"
                  placeholder="搜索本校区商品"
                  prefix-icon="el-icon-search"
                  size="small"
                  style="width: 300px;"
                  @input="filterOwnGoods"
                />
                <el-select
                  v-model="ownStatusFilter"
                  placeholder="商品状态"
                  size="small"
                  style="width: 120px; margin-left: 10px;"
                  @change="filterOwnGoods"
                >
                  <el-option label="全部状态" value="" />
                  <el-option label="上架" :value="0" />
                  <el-option label="下架" :value="1" />
                </el-select>
                <el-select
                  v-model="ownDistributionFilter"
                  placeholder="分销状态"
                  size="small"
                  style="width: 120px; margin-left: 10px;"
                  @change="filterOwnGoods"
                >
                  <el-option label="全部" value="" />
                  <el-option label="支持分销" :value="0" />
                  <el-option label="不支持分销" :value="1" />
                </el-select>
              </div>
              <div class="action-buttons">
                <el-button @click="selectAllOwnGoods" size="small" type="primary">
                  全选本校区商品
                </el-button>
                <el-button @click="clearOwnSelection" size="small">
                  清空选择
                </el-button>
              </div>
            </div>

            <div class="goods-grid">
              <div
                v-for="goods in filteredOwnGoods"
                :key="'own-' + goods.goodId"
                class="goods-card"
                :class="{ 'selected': isSelectedOwn(goods) }"
                @click="toggleOwnGoodsSelection(goods)"
              >
                <div class="goods-image">
                  <img :src="goods.goodPicture || '/images/placeholder.jpg'" :alt="goods.goodName" @error="handleImageError" />
                  <div class="goods-overlay">
                    <i v-if="isSelectedOwn(goods)" class="el-icon-check selected-icon"></i>
                  </div>
                </div>
                <div class="goods-info">
                  <h4 class="goods-name">{{ goods.goodName }}</h4>
                  <p class="goods-classify">{{ goods.goodClassify }}</p>
                  <div class="goods-price">
                    <span class="original-price">原价: ¥{{ goods.goodOriginalPrice }}</span>
                    <span class="member-price">会员价: ¥{{ goods.goodMemberPrice }}</span>
                  </div>
                  <div class="goods-meta">
                    <el-tag :type="goods.goodStatus === 0 ? 'success' : 'danger'" size="mini">
                      {{ goods.goodStatus === 0 ? '上架' : '下架' }}
                    </el-tag>
                    <el-tag :type="goods.isDistribution === 0 ? 'primary' : 'info'" size="mini" style="margin-left: 4px;">
                      {{ goods.isDistribution === 0 ? '支持分销' : '不支持分销' }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>

            <div v-if="filteredOwnGoods.length === 0" class="empty-state">
              <i class="el-icon-box"></i>
              <p>暂无本校区商品</p>
            </div>
          </div>
        </el-tab-pane>

        <!-- 分销商品tab -->
        <el-tab-pane label="分销商品" name="distribution">
          <template slot="label">
            <i class="el-icon-share"></i>
            分销商品 ({{ selectedDistributionGoods.length }})
          </template>

          <div class="distribution-goods-section">
            <!-- 校区选择器 -->
            <div class="campus-selector-section">
              <div class="section-title">
                <i class="el-icon-office-building"></i>
                选择分销校区
              </div>
              <div class="campus-cards">
                <div
                  v-for="campus in distributionCampusList"
                  :key="'campus-' + campus.campusId"
                  class="campus-card"
                  :class="{ 'active': selectedCampusId === campus.campusId }"
                  @click="selectDistributionCampus(campus.campusId)"
                >
                  <div class="campus-logo">
                    <img v-if="campus.campusLogoUrl" :src="campus.campusLogoUrl" :alt="campus.campusName" />
                    <i v-else class="el-icon-office-building"></i>
                  </div>
                  <div class="campus-info">
                    <h4>{{ campus.campusName }}</h4>
                    <p>{{ campus.campusAddress }}</p>
                    <span class="goods-count">{{ getCampusGoodsCount(campus.campusId) }}个商品</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 分销商品列表 -->
            <div v-if="selectedCampusId" class="distribution-goods-list">
              <div class="section-header">
                <div class="section-title">
                  <i class="el-icon-goods"></i>
                  {{ getSelectedCampusName() }} - 分销商品
                </div>
                <div class="search-bar">
                  <el-input
                    v-model="distributionSearchKeyword"
                    placeholder="搜索分销商品"
                    prefix-icon="el-icon-search"
                    size="small"
                    style="width: 300px;"
                    @input="filterDistributionGoods"
                  />
                  <el-button @click="selectAllDistributionGoods" size="small" type="primary" style="margin-left: 10px;">
                    全选当前校区
                  </el-button>
                  <el-button @click="clearDistributionSelection" size="small">
                    清空选择
                  </el-button>
                </div>
              </div>

              <div class="goods-grid">
                <div
                  v-for="goods in filteredDistributionGoods"
                  :key="'dist-' + goods.goodId"
                  class="goods-card distribution-card"
                  :class="{ 'selected': isSelectedDistribution(goods) }"
                  @click="toggleDistributionGoodsSelection(goods)"
                >
                  <div class="goods-image">
                    <img :src="goods.goodPicture || '/images/placeholder.jpg'" :alt="goods.goodName" @error="handleImageError" />
                    <div class="goods-overlay">
                      <i v-if="isSelectedDistribution(goods)" class="el-icon-check selected-icon"></i>
                    </div>
                  </div>
                  <div class="goods-info">
                    <h4 class="goods-name">{{ goods.goodName }}</h4>
                    <p class="goods-classify">{{ goods.goodClassify }}</p>
                    <div class="goods-price">
                      <span class="original-price">原价: ¥{{ goods.goodOriginalPrice }}</span>
                      <span class="member-price">会员价: ¥{{ goods.goodMemberPrice }}</span>
                    </div>
                    <div class="goods-commission">
                      <span class="commission-rate">佣金比例: {{ goods.goodCommissionRate }}%</span>
                    </div>
                    <div class="goods-meta">
                      <el-tag type="primary" size="mini">来自: {{ getCampusName(goods.campusId) }}</el-tag>
                      <el-tag type="success" size="mini" style="margin-left: 4px;">分销商品</el-tag>
                    </div>
                  </div>
                </div>
              </div>

              <div v-if="filteredDistributionGoods.length === 0" class="empty-state">
                <i class="el-icon-share"></i>
                <p>该校区暂无分销商品</p>
              </div>
            </div>

            <div v-else class="select-campus-hint">
              <i class="el-icon-office-building"></i>
              <p>请选择一个校区查看其分销商品</p>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 底部操作区 -->
    <div class="manager-footer">
      <div class="selection-summary">
        <span>已选择: 本校区商品 {{ selectedOwnGoods.length }} 个，分销商品 {{ selectedDistributionGoods.length }} 个</span>
      </div>
      <div class="footer-actions">
        <el-button @click="$emit('close')" size="small">取消</el-button>
        <el-button 
          @click="confirmSelection" 
          type="primary" 
          size="small"
          :disabled="selectedOwnGoods.length === 0 && selectedDistributionGoods.length === 0"
        >
          确认选择 ({{ selectedOwnGoods.length + selectedDistributionGoods.length }})
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getOwnCampusGoods, getDistributionCampusList, getDistributionGoods } from '@/api/artGood/artGood'

export default {
  name: 'DistributionGoodsManager',
  props: {
    currentCampusId: {
      type: [Number, String],
      required: true
    },
    selected: {
      type: Array,
      default: () => []
    },
    isAdmin: {
      type: Boolean,
      default: false
    },
    campusList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: false,
      activeTab: 'own',
      
      // 本校区商品相关
      ownGoods: [],
      filteredOwnGoods: [],
      selectedOwnGoods: [],
      ownSearchKeyword: '',
      ownStatusFilter: '',
      ownDistributionFilter: '',
      
      // 分销相关
      distributionCampusList: [],
      selectedCampusId: null,
      distributionGoods: [],
      filteredDistributionGoods: [],
      selectedDistributionGoods: [],
      distributionSearchKeyword: '',
      
      // 商品数量统计
      campusGoodsCount: {}
    }
  },
  mounted() {
    this.initializeData()
  },
  methods: {
    // 初始化数据
    async initializeData() {
      this.loading = true
      try {
        // 初始化已选中的商品
        this.initializeSelectedGoods()
        
        // 并行加载数据
        await Promise.all([
          this.loadOwnCampusGoods(),
          this.loadDistributionCampusList()
        ])
      } catch (error) {
        console.error('初始化数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    // 初始化已选中的商品
    initializeSelectedGoods() {
      if (this.selected && this.selected.length > 0) {
        // 分离本校区商品和分销商品
        this.selectedOwnGoods = this.selected.filter(goods => goods.campusId === this.currentCampusId)
        this.selectedDistributionGoods = this.selected.filter(goods => goods.campusId !== this.currentCampusId)
      }
    },

    // 加载本校区商品
    async loadOwnCampusGoods() {
      try {
        const response = await getOwnCampusGoods(this.currentCampusId)
        if (response && response.code === 200) {
          this.ownGoods = response.rows || response.data || []
          this.filteredOwnGoods = [...this.ownGoods]
        } else {
          // 模拟数据
          this.ownGoods = [
            {
              goodId: 1,
              goodName: '油画基础课程',
              goodClassify: '绘画课程',
              goodPicture: '/images/course-oil-painting.jpg',
              goodOriginalPrice: 299.00,
              goodMemberPrice: 199.00,
              goodCommissionRate: 15,
              goodStatus: 0,
              isDistribution: 0,
              campusId: this.currentCampusId
            },
            {
              goodId: 2,
              goodName: '素描入门套装',
              goodClassify: '绘画用品',
              goodPicture: '/images/drawing-kit.jpg',
              goodOriginalPrice: 158.00,
              goodMemberPrice: 128.00,
              goodCommissionRate: 20,
              goodStatus: 0,
              isDistribution: 0,
              campusId: this.currentCampusId
            }
          ]
          this.filteredOwnGoods = [...this.ownGoods]
        }
      } catch (error) {
        console.error('加载本校区商品失败:', error)
        this.ownGoods = []
        this.filteredOwnGoods = []
      }
    },

    // 加载可分销的校区列表
    async loadDistributionCampusList() {
      try {
        const response = await getDistributionCampusList()
        if (response && response.code === 200) {
          this.distributionCampusList = response.rows || response.data || []
        } else {
          // 使用传入的校区列表作为备用
          this.distributionCampusList = this.campusList.filter(campus => 
            campus.campusId !== this.currentCampusId && campus.campusIsRecommended === 0
          )
        }
        
        // 统计每个校区的商品数量
        this.countCampusGoods()
      } catch (error) {
        console.error('加载分销校区列表失败:', error)
        this.distributionCampusList = this.campusList.filter(campus => 
          campus.campusId !== this.currentCampusId
        )
        this.countCampusGoods()
      }
    },

    // 统计校区商品数量
    async countCampusGoods() {
      for (const campus of this.distributionCampusList) {
        try {
          const response = await getDistributionGoods(campus.campusId)
          const goods = response?.rows || response?.data || []
          this.campusGoodsCount[campus.campusId] = goods.length
        } catch (error) {
          this.campusGoodsCount[campus.campusId] = 0
        }
      }
    },

    // 选择分销校区
    async selectDistributionCampus(campusId) {
      if (this.selectedCampusId === campusId) return
      
      this.selectedCampusId = campusId
      this.loading = true
      
      try {
        const response = await getDistributionGoods(campusId)
        if (response && response.code === 200) {
          this.distributionGoods = response.rows || response.data || []
        } else {
          // 模拟分销商品数据
          this.distributionGoods = [
            {
              goodId: 101,
              goodName: '水彩画高级课程',
              goodClassify: '绘画课程',
              goodPicture: '/images/course-watercolor.jpg',
              goodOriginalPrice: 399.00,
              goodMemberPrice: 299.00,
              goodCommissionRate: 25,
              goodStatus: 0,
              isDistribution: 0,
              campusId: campusId
            },
            {
              goodId: 102,
              goodName: '专业画笔套装',
              goodClassify: '绘画用品',
              goodPicture: '/images/brush-set.jpg',
              goodOriginalPrice: 288.00,
              goodMemberPrice: 218.00,
              goodCommissionRate: 18,
              goodStatus: 0,
              isDistribution: 0,
              campusId: campusId
            }
          ]
        }
        this.filteredDistributionGoods = [...this.distributionGoods]
      } catch (error) {
        console.error('加载分销商品失败:', error)
        this.distributionGoods = []
        this.filteredDistributionGoods = []
      } finally {
        this.loading = false
      }
    },

    // 过滤本校区商品
    filterOwnGoods() {
      let filtered = [...this.ownGoods]
      
      // 搜索过滤
      if (this.ownSearchKeyword) {
        filtered = filtered.filter(goods => 
          goods.goodName.toLowerCase().includes(this.ownSearchKeyword.toLowerCase()) ||
          goods.goodClassify.toLowerCase().includes(this.ownSearchKeyword.toLowerCase())
        )
      }
      
      // 状态过滤
      if (this.ownStatusFilter !== '') {
        filtered = filtered.filter(goods => goods.goodStatus === this.ownStatusFilter)
      }
      
      // 分销状态过滤
      if (this.ownDistributionFilter !== '') {
        filtered = filtered.filter(goods => goods.isDistribution === this.ownDistributionFilter)
      }
      
      this.filteredOwnGoods = filtered
    },

    // 过滤分销商品
    filterDistributionGoods() {
      let filtered = [...this.distributionGoods]
      
      if (this.distributionSearchKeyword) {
        filtered = filtered.filter(goods => 
          goods.goodName.toLowerCase().includes(this.distributionSearchKeyword.toLowerCase()) ||
          goods.goodClassify.toLowerCase().includes(this.distributionSearchKeyword.toLowerCase())
        )
      }
      
      this.filteredDistributionGoods = filtered
    },

    // 切换本校区商品选择
    toggleOwnGoodsSelection(goods) {
      const index = this.selectedOwnGoods.findIndex(item => item.goodId === goods.goodId)
      if (index > -1) {
        this.selectedOwnGoods.splice(index, 1)
      } else {
        this.selectedOwnGoods.push(goods)
      }
    },

    // 切换分销商品选择
    toggleDistributionGoodsSelection(goods) {
      const index = this.selectedDistributionGoods.findIndex(item => item.goodId === goods.goodId)
      if (index > -1) {
        this.selectedDistributionGoods.splice(index, 1)
      } else {
        this.selectedDistributionGoods.push(goods)
      }
    },

    // 检查本校区商品是否被选中
    isSelectedOwn(goods) {
      return this.selectedOwnGoods.some(item => item.goodId === goods.goodId)
    },

    // 检查分销商品是否被选中
    isSelectedDistribution(goods) {
      return this.selectedDistributionGoods.some(item => item.goodId === goods.goodId)
    },

    // 全选本校区商品
    selectAllOwnGoods() {
      this.selectedOwnGoods = [...this.filteredOwnGoods]
    },

    // 清空本校区选择
    clearOwnSelection() {
      this.selectedOwnGoods = []
    },

    // 全选当前校区分销商品
    selectAllDistributionGoods() {
      this.selectedDistributionGoods = [
        ...this.selectedDistributionGoods.filter(goods => goods.campusId !== this.selectedCampusId),
        ...this.filteredDistributionGoods
      ]
    },

    // 清空分销商品选择
    clearDistributionSelection() {
      this.selectedDistributionGoods = this.selectedDistributionGoods.filter(goods => 
        goods.campusId !== this.selectedCampusId
      )
    },

    // 获取校区商品数量
    getCampusGoodsCount(campusId) {
      return this.campusGoodsCount[campusId] || 0
    },

    // 获取选中校区名称
    getSelectedCampusName() {
      const campus = this.distributionCampusList.find(c => c.campusId === this.selectedCampusId)
      return campus ? campus.campusName : ''
    },

    // 获取校区名称
    getCampusName(campusId) {
      const campus = this.distributionCampusList.find(c => c.campusId === campusId) || 
                   this.campusList.find(c => c.campusId === campusId)
      return campus ? campus.campusName : '未知校区'
    },

    // 处理图片错误
    handleImageError(event) {
      event.target.src = '/images/placeholder.jpg'
    },

    // Tab切换
    handleTabChange(tab) {
      this.activeTab = tab.name
    },

    // 刷新数据
    refreshData() {
      this.initializeData()
    },

    // 确认选择
    confirmSelection() {
      const allSelected = [...this.selectedOwnGoods, ...this.selectedDistributionGoods]
      this.$emit('select', allSelected)
      this.$message.success(`已选择 ${allSelected.length} 个商品`)
    }
  }
}
</script>

<style scoped>
.distribution-goods-manager {
  height: 70vh;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.manager-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e1e6f0;
  background: #fafbfc;
}

.header-left h3 {
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-size: 18px;
}

.header-left .description {
  color: #666;
  font-size: 13px;
}

.manager-content {
  flex: 1;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 0 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-bar {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
  padding: 4px;
}

.goods-card {
  border: 2px solid #e1e6f0;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff;
  position: relative;
}

.goods-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.goods-card.selected {
  border-color: #67c23a;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.25);
}

.goods-card.distribution-card {
  background: linear-gradient(135deg, #fff 0%, #f8f9ff 100%);
}

.goods-image {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-overlay {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.goods-card.selected .goods-overlay {
  opacity: 1;
  background: #67c23a;
}

.selected-icon {
  color: white;
  font-size: 14px;
}

.goods-info {
  padding: 12px;
}

.goods-name {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.goods-classify {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #666;
}

.goods-price {
  margin-bottom: 8px;
}

.original-price {
  display: block;
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.member-price {
  display: block;
  font-size: 14px;
  color: #e74c3c;
  font-weight: 600;
}

.goods-commission {
  margin-bottom: 8px;
}

.commission-rate {
  font-size: 12px;
  color: #f39c12;
  background: #fef9e7;
  padding: 2px 6px;
  border-radius: 3px;
}

.goods-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.campus-selector-section {
  margin-bottom: 24px;
}

.campus-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 12px;
  margin-top: 12px;
}

.campus-card {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 2px solid #e1e6f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff;
}

.campus-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.campus-card.active {
  border-color: #409eff;
  background: #ecf5ff;
}

.campus-logo {
  width: 48px;
  height: 48px;
  margin-right: 12px;
  border-radius: 6px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
}

.campus-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.campus-logo i {
  font-size: 24px;
  color: #666;
}

.campus-info h4 {
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-size: 14px;
  font-weight: 600;
}

.campus-info p {
  margin: 0 0 4px 0;
  color: #666;
  font-size: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.goods-count {
  font-size: 11px;
  color: #409eff;
  background: #ecf5ff;
  padding: 2px 6px;
  border-radius: 3px;
}

.select-campus-hint {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.select-campus-hint i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.manager-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-top: 1px solid #e1e6f0;
  background: #fafbfc;
}

.selection-summary {
  color: #666;
  font-size: 14px;
}

.footer-actions {
  display: flex;
  gap: 8px;
}

/* Tab样式优化 */
::v-deep .el-tabs__header {
  margin: 0;
  background: #fafbfc;
  border-bottom: 1px solid #e1e6f0;
}

::v-deep .el-tabs__content {
  padding: 20px;
  height: calc(100% - 40px);
  overflow-y: auto;
}

::v-deep .el-tab-pane {
  height: 100%;
}
</style> 